package edu.demo.recommend.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.demo.recommend.advice.AdminPermission;
import edu.demo.recommend.common.CommonUtils;
import edu.demo.recommend.common.ResultCodeEnum;
import edu.demo.recommend.exception.RecommendBusinessException;
import edu.demo.recommend.pojo.Seller;
import edu.demo.recommend.request.PageQuery;
import edu.demo.recommend.request.SellerReq;
import edu.demo.recommend.service.SellerService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @author hb
 */
@Controller
@RequestMapping("/admin/seller/")
public class SellerManagerController {

    @Resource
    private SellerService sellerService;

   @RequestMapping("/index")
   @AdminPermission
    public ModelAndView index(PageQuery pageQuery){
       //利用PageHelper插件进行分页的设置(起始页、页面大小)
       PageHelper.startPage(pageQuery.getPage(), pageQuery.getSize());
       List<Seller> sellers = sellerService.selectAll();
       PageInfo<Seller> pageInfo = new PageInfo<>(sellers);

       ModelAndView mv = new ModelAndView("/admin/seller/index.html");
       mv.addObject("CONTROLLER_NAME","seller");
       mv.addObject("ACTION_NAME","index");
       mv.addObject("data",pageInfo);


       return mv;

    }


    @RequestMapping("/createPage")
    @AdminPermission
    public ModelAndView createPage(){
        ModelAndView mv = new ModelAndView("/admin/seller/create.html");
        mv.addObject("CONTROLLER_NAME","seller");
        mv.addObject("ACTION_NAME","create");
        return mv;
    }

    @RequestMapping("/create")
    @AdminPermission
    public String create(@Valid SellerReq sellerReq, BindingResult bindingResult){
       if(bindingResult.hasErrors()){
           throw new RecommendBusinessException(ResultCodeEnum.REQUEST_PARAM_ERROR, CommonUtils.processErrorMessage(bindingResult));
       }
        Seller seller = new Seller();
        seller.setName(sellerReq.getName());
        sellerService.create(seller);
        return "redirect:/admin/seller/index";
    }
}
